var app = new Vue({
  el: '#app',
  data () {
    return {
        layerShow: false, // 区域/分类弹出层是否显示
        typeId: 1, // tab切换点击id
        oldId: '', // tab切换之前id
        curIndex: 0,
        regions: [ // 区域/分类列表数据
            {
            id: 0,
            name: '请选择',
            list: []
            },
            {
            id: 0,
            name: '',
            list: []
            },
            {
            id: 0,
            name: '',
            list: []
            },
            {
            id: 0,
            name: '',
            list: []
            },
            {
            id: 0,
            name: '',
            list: []
            },
            {
            id: 0,
            name: '',
            list: []
            }
        ],
        curList: [], // 区域/分类当前列表数据
        goodslist: null, // 商品列表数据
        sreachValue: "", // 品牌搜索框关键字
        Top: "", // 品牌搜索框top
        Left: "", // 品牌搜索框left
        Height: "", // 品牌搜索框height
        brandlist: null, // 品牌弹出下拉列表数据
        brandName: "", // 品牌名字
        communityId: "", // 小区id
        categoryId: "", // 分类id
        currentPage: 1, // 当前页数
        totalPage: 2, // 总页数
        pageSize: 10, // 一页显示多少条
        loading: true,
        marketlist: null, // 其它超市数据
        position: 'bottom', // 加入购物车弹窗位置
        num: 1, // 加入购物车商品数量
        showPopup: false, // 更多超市价格弹窗是否展示
        popupTop: '', // 更多超市价格弹窗位置
        addCartIndex: 0, // 加入购物车弹窗当前商品下标
        popupIndex: 0, // 更多超市价格弹窗当前商品下标
        popupTriangle: '', // 更多超市价格弹窗三角位置
        triangleStyle: '', // 更多超市价格弹窗样式
        scrollTop: 0, // 页面当前偏移量
    }
  },
  created() {
      this.getAddress()
  },
  watch: {
    curIndex (val) {
      this.curList = this.regions[val].list
    },
    regions: {
      deep: true,
      handler (val) {
        this.curList = val[this.curIndex].list
      }
    },
    sreachValue (val) {
      if (val!=="") {
        this.getBrandName(val)
      }
    }
  },
  computed: {    
    Style () {      
      return this.sreachValue === "" ? {
        top: this.Top + this.Height
      } : {
        top: this.Top + this.Height
      }
    }
  },
  methods: {
    // 返回
    goback () {
      window.history.go(-1);
    }, 
    // 获取综合数据
    getAll () {
      this.loading = true
      this.currentPage = 1
      this.goodslist = []
      this.getData() 
    },
    // 滚动加载更多商品
    loadMore(){
        this.currentPage ++
        if(this.currentPage > this.totalPage){
          this.loading = true
            return false
        }
        this.getData()
    },
    // 获取商品数据
    getData () {
      Axios.post('/goods/goods/differenceRanking.do', {
        currentPage: this.currentPage,
        pageSize: this.pageSize,
        brandName  : this.brandName,
        communityId: this.communityId,
        categoryId: this.categoryId
      }).then(res => {
        if (res.respCode === "S") {
          let list = res.data.data
          list.forEach(goods => {
            goods.minPrice = goods.minPrice / 100
            goods.maxPrice = goods.maxPrice / 100
          });
          if (this.currentPage == 1) {
            this.goodslist = list
          } else {
            this.goodslist = this.goodslist.concat(list)
          }
          this.totalPage = res.data.totalPage
          this.currentPage = res.data.currentPage

          if (this.currentPage >= this.totalPage) {
            this.loading = true
          } else {
            this.loading = false
          }
        } else {
          this.goodslist = []
        }       			
      }).catch(err => {
        console.error(err)
      })
    },
    getAddress () {
      let accessToken = getCookie('accessToken')
      if (accessToken) {
        Axios.post('/user/address/getDefaultReceiveAddress.do', {}).then(res => {
          if (res.respCode === "S") {            
            this.getAll()
          } else {
              this.$createDialog({
                  type: 'confirm',
                  title: '温馨提示',
                  content: '您没有设置默认收货地址！',
                  confirmBtn: {
                      text: '去设置',
                      active: true,
                      disabled: false,
                      href: '../my/my_shouhuo.html'
                  },
                  cancelBtn: {
                      text: '取消',
                      active: false,
                      disabled: false,
                      href: '../'
                  }
              }).show()
          }
        }).catch(err => {
          console.error(err)
        })
      }
    },
    // 点击综合
    changeAll () {
      this.typeId = 1
      this.getAll()
    },
    // 点击区域
    changeArea () {
      this.oldId = this.typeId
      this.typeId = 2
      this.layerShow = true
      this.getArea()
    },
    // 获取区域数据
    getArea () {
      Axios.post('/area/area/getAllArea.do', {}).then(res => {
        this.regions[this.curIndex].list = res.data
      }).catch(err => {
        console.error(err)
      })
    },
    // 点击分类
    changeCategory () {
      this.oldId = this.typeId
      this.typeId = 3
      this.layerShow = true
      this.getCategory()
    },
    // 获取分类数据
    getCategory () {
      Axios.post('/goods/category/showAllCategory.do', {}).then(res => {
        this.regions[this.curIndex].list = res.data
      }).catch(err => {
        console.error(err)
      })
    },
    // 点击品牌
    changeBrand () {
      this.goodslist = null
      this.typeId = 4
      this.$nextTick(() => {
        this.sreachValue = ""
        this.Top = this.$refs.sreachInput.getBoundingClientRect().top
        this.Height = this.$refs.sreachInput.getBoundingClientRect().height
      })
    },
    // 品牌输入框获取品牌列表数据
    getBrandName (val) {
      Axios.post('/brand/brand/searchBrand.do', {
        brandName: val
      }).then(res => {
        this.brandlist = res.data.slice(0, 10)
      }).catch(err => {
        console.error(err)
      })
    },
    // 品牌列表点击获取商品列表
    getBrand (index) {
      this.communityId = ""
      this.categoryId = ""
      this.brandName = this.brandlist[index].name
      this.getAll()
    },
    searchBrand (event) {
      if (event.keyCode == 13) {
        event.preventDefault()
        this.communityId = ""
        this.categoryId = ""
        this.brandName = this.sreachValue
        this.getAll()
      }        
    },
    // 区域和分类分级获取数据
    select (list) {
      this.regions[this.curIndex].name = list.name
      if (list.hasOwnProperty("code") || list.hasOwnProperty("smallCommunityId")) { // 区域按分级获取数据
        this.regions[this.curIndex].id = list.code
        if (this.curIndex < 3) {
          this.curIndex++
          this.regions[this.curIndex].name = '请选择'
          this.regions[this.curIndex].list = list.child
        } else if (this.curIndex === 3) { // 区域最后一级获取小区数据
          this.curIndex++
          this.regions[this.curIndex].name = '请选择'
          Axios.post('/area/SmallCommunity/getSmallCommunity.do', {
            areaCode: list.code
          }).then(res => {            
            this.curList = res.data
          }).catch(err => {
            console.error(err)
          })          
        } else { // 按小区获取数据
          this.brandName = ""
          this.categoryId = ""
          this.communityId = list.communityId
          this.getAll()
          this.close()
          this.typeId = 2
        }
      } else { // 分类按分级获取数据
        this.regions[this.curIndex].id = list.categoryId
        if (this.curIndex < 2) {
          this.curIndex++
          this.regions[this.curIndex].name = '请选择'
          this.regions[this.curIndex].list = list.children
        } else if (this.curIndex === 2) { // 按3级分类Id获取商品列表数据
          this.brandName = ""
          this.communityId = ""
          this.categoryId = list.categoryId
          this.getAll()
          this.close()
          this.typeId = 3
        }
      }
    },
    // 区域和分类弹框tab切换处理
    changeTab (index) {
      this.curIndex = index
      this.regions[index].name = '请选择'
      for (let i = index + 1; i < 5; i++) {
        this.regions[i] = {
          id: 0,
          name: '',
          list: []
        }
      }
    },
    // 区域和分类弹框关闭按钮
    close () {
      this.curIndex = 0
      this.regions[0].name = '请选择'
      for (let i = 1; i < 5; i++) {
        this.regions[i] = {
          id: 0,
          name: '',
          list: []
        }
      }
      this.curList = null
      this.layerShow = false
      this.typeId = this.oldId
    },
    // 直接下单
    placeOrder (index) {
        this.num = 1
        this.addCartIndex = index
        this.$refs.myPopup4.show()
    },
    // 直接购买
    toBUy () {
        let goodsSkuId = this.goodslist[this.addCartIndex].goodsSkuId
        let quantity = this.num
        window.location.href = '../shopping/order.html?goodsSkuId=' + goodsSkuId + '&quantity=' + quantity
    },
    // 加入购物车减号
    reduce () {
        if (this.num > 1) {
            this.num--
        }
    },
    // 加入购物车加号
    plus () {
        if (this.num < 99)  {
            this.num++
        }
    },
    // 加入购物车按钮
    addCart () {
        Axios.post('goods/shopCar/addShopCar.do', {
            goodsSkuId: this.goodslist[this.addCartIndex].goodsSkuId,
            quantity: this.num
        }).then(res => {
            if (res.respCode === 'S') {
                const toast = this.$createToast({
                    txt: '您已提交成功<br/>请到购物车查看',
                    type: 'correct'
                })                    
                this.$refs.myPopup4.hide()
                toast.show()
            }
        })
    },
    // 更多价格弹窗
    morePrice (e, index) {
        this.popupIndex = index
        let dom = e.currentTarget
        let bodyHeight = document.body.clientHeight
        let top = dom.previousElementSibling.getBoundingClientRect().top
        let height = dom.previousElementSibling.getBoundingClientRect().height
        let popupTop
        let size = getComputedStyle(window.document.documentElement)['font-size']
        size = Number(size.substring(0, size.length - 2))
        let popupHeight = 4.3 * size
        if ((bodyHeight - top) > (popupHeight + 10)) {
            popupTop = top + height
            this.popupTriangle = 'top'
            let left = dom.getBoundingClientRect().left - (0.05 * size) - (0.72 * size)
            this.triangleStyle = 'top: -0.33rem; left:' + left
            this.popupTop = 'top:' + popupTop
        } else {
            popupTop = top - popupHeight
            this.popupTriangle = 'bottom'
            let left = dom.getBoundingClientRect().left - (0.05 * size) - (0.72 * size)
            this.triangleStyle = 'top:' + popupHeight + ';left:' + left
            this.popupTop = 'top:' + popupTop
        }
        Axios.post('goods/goods/supermarketPriceList.do', {
            goodsSkuId: this.goodslist[this.popupIndex].goodsSkuId
        }).then(res => {
            if (res.respCode === 'S') {
                let list = res.data.supermarketGoodsList
                list.forEach(goods => {
                    if (goods.price == -1) {
                      goods.price = "无价格/无货"
                    } else {
                      goods.price = goods.price / 100 + "元"
                    }          
                })
                this.marketlist = list
                dom.style.opacity = 0
                this.showPopup = true
            }
        })
        let bodyEl = document.body
        this.scrollTop = window.scrollY
        bodyEl.style.position = 'fixed'
        bodyEl.style.top = -this.scrollTop
    },
    // 关闭更多价格弹窗
    closePopup () {
        let triangle = document.querySelectorAll('.search-goodsTriangle')
        triangle[this.popupIndex].style.opacity = 1
        let popupMarket = document.querySelector('.search-popupMarket')
        popupMarket.scrollTop = 0
        this.showPopup = false
        let bodyEl = document.body
        bodyEl.style.position = ''
        bodyEl.style.top = ''        
        window.scrollTo(0, this.scrollTop)
    }
  }
})